package com.softcits.hw.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Component;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;

@Component
public class UserService implements IUserService {
    
    @Autowired()
    @Qualifier("jdbcTemplate")
    private JdbcTemplate template;
    
    @Autowired
    private PlatformTransactionManager transaction;

    public void insert(int mode) {
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        TransactionStatus status = transaction.getTransaction(def);
        
        String sql = "insert into t1 (name) values (?);";
        template.update(sql, "liu1");
        template.update(sql, "liu2");
        if(mode == 0) {
            transaction.rollback(status);
            throw new RuntimeException("failed ... batch insert ");
        }
        template.update(sql, "user1");
        transaction.commit(status);
    }
    
    public void insertUser(int mode) {
        
        String sql = "insert into t1 (name) values (?);";
        template.update(sql, "liu1");
        template.update(sql, "liu2");
        if(mode == 0) {
            throw new RuntimeException("failed ... batch insert ");
        }
        template.update(sql, "liu3");
    }
}
